package com.skeeey.aim.service.dao.impl;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;

import com.skeeey.aim.model.AutoRecord;
import com.skeeey.aim.service.dao.AutoRecordDao;

public class AutoRecordDaoImpl extends TempleteDaoImpl<AutoRecord, String> implements AutoRecordDao {

	@Override
	public void saveAutoRecords(List<AutoRecord> records) {
		Session session = this.getSession();
		for (int i = 0; i < records.size(); i++) {
			session.save(records.get(i));
			if (i % 50 == 0) {
				session.flush();
				session.clear();
			}
		}
		
		session.flush();
		session.clear();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<AutoRecord> findRecordBy(String dealerCode, String vinCode) {
		DetachedCriteria criteria = DetachedCriteria.forClass(AutoRecord.class);
		criteria.add(Restrictions.eq("dealerCode", dealerCode));
		criteria.add(Restrictions.like("VINCode", "%" + vinCode));
		return this.getHibernateTemplate().findByCriteria(criteria);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<AutoRecord> findRecordBy(String vinCode) {
		DetachedCriteria criteria = DetachedCriteria.forClass(AutoRecord.class);
		criteria.add(Restrictions.like("VINCode", "%" + vinCode));
		return this.getHibernateTemplate().findByCriteria(criteria);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<AutoRecord> getRecordsBy(int status, String timeStamp, String dealerCode) {
		DetachedCriteria criteria = DetachedCriteria.forClass(AutoRecord.class);
		criteria.add(Restrictions.eq("status", status));
		criteria.add(Restrictions.eq("timeStamp", timeStamp));
		criteria.add(Restrictions.eq("dealerCode", dealerCode));
		return this.getHibernateTemplate().findByCriteria(criteria);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<AutoRecord> getRecordsBy(String vinCode, String timeStamp) {
		DetachedCriteria criteria = DetachedCriteria.forClass(AutoRecord.class);
		criteria.add(Restrictions.like("VINCode", "%" + vinCode));
		criteria.add(Restrictions.eq("timeStamp", timeStamp));
		return this.getHibernateTemplate().findByCriteria(criteria);
	}

	@Override
	public void deleteAutoRecords(String dealerCode, String timeStamp) {
		Session session = this.getSession();
		Transaction tx = session.beginTransaction();
		session.createQuery("delete AutoRecord r where r.dealerCode=:dealerCode and r.timeStamp=:timeStamp")
			.setString("dealerCode", dealerCode)
			.setString("timeStamp", timeStamp)
			.executeUpdate();
		tx.commit();
	}

}
